package com.xqboss.web.core.config;

import cn.hutool.core.util.ObjectUtil;
import com.google.common.collect.Maps;
import com.xqboss.common.enums.BaseEnum;
import com.xqboss.common.exception.ServiceException;
import org.springframework.core.convert.converter.Converter;

import java.util.Map;

/**
 * <p>
 * 枚举编码 -> 枚举 转化器
 * </p>
 * @author Trent
 * @date 2023/8/19
 */

public class IntegerToEnumConverter<T extends BaseEnum<Integer>> implements Converter<Integer, T> {
    private Map<Integer, T> enumMap = Maps.newHashMap();

    public IntegerToEnumConverter(Class<T> enumType) {
        T[] enums = enumType.getEnumConstants();
        for (T e : enums) {
            enumMap.put(e.getValue(), e);
        }
    }

    @Override
    public T convert(Integer source) {
        if(source == null){
            return null;
        }
        T t = enumMap.get(source);
        if (ObjectUtil.isNull(t)) {
            throw new ServiceException("选择类型错误！！！");
        }
        return t;
    }
}